//
//  110. 平衡二叉树.swift
//  Top600
//
//  Created by rjb on 2021/7/27.
//

import Foundation
class Solution110 {
    // 是否是平衡二叉树
    func isBalanced(_ root: TreeNode?) -> Bool {
        let height = deep(root)
        return height == -1 ? false : true
    }
    func deep(_ node: TreeNode?) -> Int {
        guard let node = node else {
            return 0
        }
        let left = deep(node.left)
        if left == -1 {
            return -1
        }
        let right = deep(node.right)
        if right == -1 {
            return -1
        }
        if abs(left - right) >= 2 {
           return -1
        }
        return max(left, right) + 1
    }
    static func test() {
        let node1 = TreeNode(1)
        let node2 = TreeNode(2)
        let node22 = TreeNode(2)
        let node3 = TreeNode(3)
        let node33 = TreeNode(3)
        let node4 = TreeNode(7)
        let node44 = TreeNode(4)
        node1.left = node2
        node1.right = node22
        node2.left = node3
        node2.right = node3
        node3.left = node4
        node3.right = node44
       
        let solution = Solution110()
        let result = solution.isBalanced(node3)
        print(result)
    }
}
